#include "Stdafx.h"
#include "Terrain.h"

namespace Pulpy
{
	void Terrain::LoadHeightMap(char * filename)
	{
		FILE *pFile; 
		fopen_s( &pFile, filename, "rb" ); 
		if ( !pFile )
			Logger::getInstance().addLog("Terrain::Error Loading Height Map: ", false);
		else
			Logger::getInstance().addLog("Terrain::Loaded Height Map: ", false);
		Logger::getInstance().addLog(filename);
		fread( _HeightMap, _TerrainSize * _TerrainSize, 1, pFile );
		fclose(pFile);
	}

	void Terrain::draw()
	{
		if(!_RenderMesh) 
			glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); 
		else 
			glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
		glEnable(GL_TEXTURE_2D); // Draw terrain 
		glBindTexture(GL_TEXTURE_2D, _Image.texID );
		glPushMatrix();
		for (int z = 0; z < _TerrainSize - 1; ++z) {
			glBegin(GL_TRIANGLE_STRIP);
			for (int x = 0; x < _TerrainSize; ++x) {
				float scaledHeight = _HeightMap[z * _TerrainSize + x] / _ScaleFactor;
				float nextScaledHeight = _HeightMap[(z + 1)* _TerrainSize + x] / _ScaleFactor;
				float color = 0.5f + 0.5f * scaledHeight / _MaxHeight;
				float nextColor = 0.5f + 0.5f * nextScaledHeight / _MaxHeight;
				glColor3f(color, color, color);
				glTexCoord2f((GLfloat)x/_TerrainSize, scaledHeight/_MaxHeight);
				glVertex3f(static_cast<GLfloat>(x - _TerrainSize/2), scaledHeight,
				static_cast<GLfloat>(z - _TerrainSize/2));
				glColor3f(nextColor, nextColor, nextColor);
				glTexCoord2f((GLfloat)z/_TerrainSize, nextScaledHeight/_MaxHeight);
				glVertex3f(static_cast<GLfloat>(x - _TerrainSize/2), nextScaledHeight,
				static_cast<GLfloat>(z + 1 - _TerrainSize/2));
			}
			glEnd();
		}
		glPopMatrix();
		glDisable(GL_TEXTURE_2D);
	}
}